import { get, set } from 'lodash'
import { FileExtension } from '../../external/i18n-extract-cli/types'

export function getPrettierParser(ext: string): string {
  switch (ext) {
    case 'vue':
      return 'vue'
    case 'ts':
    case 'tsx':
      return 'babel-ts'
    default:
      return 'babel'
  }
}

export function getAllKeys(obj: Record<string, any>, prefix = '') {
  let keys: string[] = []
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      const newKey = prefix ? `${prefix}.${key}` : key
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        // 如果是对象，则递归调用
        keys = keys.concat(getAllKeys(obj[key], newKey))
      } else {
        // 如果是基本数据类型，则添加键
        keys.push(newKey)
      }
    }
  }
  return keys
}

export function findDifferentKeys(obj1: Record<string, any>, obj2: Record<string, any>) {
  const allKeys1 = getAllKeys(obj1)
  const allKeys2 = getAllKeys(obj2)
  const addKey = allKeys1.filter((key) => !allKeys2.includes(key))
  const delKey = allKeys2.filter((key) => !allKeys1.includes(key))
  return {
    addKey: [...new Set([...addKey])],
    delKey: [...new Set([...delKey])]
  }
}

const funExclude = [
  "split('",
  "import('",
  "emit('",
  "onSubmit('",
  "mount('",
  "reject('",
  "component('",
  "recoverNet('",
  "executionRequest('",
  "commit('"
]

const maxFunLen = funExclude.map((item) => item.length).reduce((a, b) => Math.max(a, b), 0)

export function extractI18nKeys(templateString: string, ext: FileExtension) {
  // let regex = /(?![a-zA-Z])\$t\('([^']+)'/g
  // if (ext !== 'vue') {
  //   regex = /(?![a-zA-Z])t\('([^']+)'/g
  // }
  const keys = []
  const regex = /t\('(i18n_.*?)'.*?\)/g
  let match
  while ((match = regex.exec(templateString)) !== null) {
    // 长度 +3 是 t('
    let subPre = templateString.substring(0, match.index + 3)
    // 避免太长的字符串
    subPre = subPre.substring(subPre.length - maxFunLen * 1.5, subPre.length)
    // console.log(subPre)
    if (funExclude.find((item) => subPre.endsWith(item))) {
      // 特殊方法
      // console.log('特殊方法')
      continue
    }
    keys.push(match[1])
  }

  // while ((match = regex.exec(templateString)) !== null) {
  //   keys.push(match[1])
  // }
  return keys
}

export function loopSet<T = any>(obj: Record<string, any>, key: string, val: T) {
  key.split('.').reduce((acc, cur, index, arr) => {
    if (index === arr.length - 1) {
      set(acc, cur, val)
    } else {
      if (!get(acc, cur)) {
        set(acc, cur, {})
      }
      return get(acc, cur)
    }
  }, obj)
}

// 递归排序json key
export function sortJSON(obj: any): any {
  if (typeof obj !== 'object' || !obj) {
    return obj
  }
  if (Array.isArray(obj)) {
    return obj.map(sortJSON)
  }
  return Object.keys(obj)
    .sort()
    .reduce((o: any, k: any) => ({ ...o, [k]: sortJSON(obj[k]) }), {})
}
